<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">信息采集与分析系统</h2>
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {loginAPI} from "../api";

const router = useRouter()

const loginForm = ref({
  username: '',
  password: ''
})

const loginRules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const loading = ref(false)
const loginFormRef = ref(null)

// 登录
const handleLogin = async () => {
  try {
    if (!loginFormRef.value) return
    // 表单验证
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    loading.value = true
    // 调用登录接口
    const response = await loginAPI.login({
      username: loginForm.value.username,
      password: loginForm.value.password
    });
    if (response.code === 0) {
      console.log(response)
      localStorage.setItem('isAuthenticated', 'true')
      localStorage.setItem('satoken', response.data.token)
      localStorage.setItem('currentUserName', loginForm.value.username)
      localStorage.setItem('currentUserIdentity', response.data.identity)
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.response?.data?.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 初始化时获取验证码
onMounted(() => {
  
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #2d3a4b;
}

.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 6px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.login-title {
  margin-bottom: 30px;
  text-align: center;
  color: #409eff;
}

.login-btn {
  width: 100%;
}

.login-container,.login-form-item {
  margin-bottom: 20px;
}
</style>
